package com.oxygen.pt.controller;

import com.oxygen.pt.pojo.dto.PressureVesselInspectionDailySaveDTO;
import com.oxygen.pt.pojo.entity.PressureVesselInspectionDaily;
import com.oxygen.pt.pojo.vo.Result;
import com.oxygen.pt.service.PressureVesselInspectionDailyService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/pv/daily")
public class PressureVesselInspectionDailyController {

    @Resource
    private PressureVesselInspectionDailyService service;

    /** 新增 */
    @PostMapping
    public Result<Void> add(@RequestBody PressureVesselInspectionDailySaveDTO dto) {
        boolean ok = service.save(dto);
        return ok ? Result.success() : Result.error("新增失败");
    }

    /** 删除 */
    @DeleteMapping("/{id}")
    public Result<Void> remove(@PathVariable Long id) {
        boolean ok = service.removeById(id);
        return ok ? Result.success() : Result.error("删除失败");
    }

    /** 查询 */
    @GetMapping("/{id}")
    public Result<PressureVesselInspectionDaily> get(@PathVariable Long id) {
        PressureVesselInspectionDaily data = service.getById(id);
        return data != null ? Result.success(data) : Result.error("记录不存在");
    }

    /** 更新 */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id,
                               @RequestBody PressureVesselInspectionDailySaveDTO dto) {
        boolean ok = service.updateById(id, dto);
        return ok ? Result.success() : Result.error("更新失败");
    }

    /**
     * 导出：压力容器日管控模板（按日期区间）
     */
    @GetMapping("/export")
    public void exportDailyControlExcel(
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            HttpServletResponse response) {

        /* 默认区间：最近30天 */
        if (startTime == null) startTime = LocalDateTime.now().minusDays(30);
        if (endTime == null)   endTime = LocalDateTime.now();

        try {
            service.exportExcel(response, startTime, endTime);
        } catch (IOException e) {
            System.out.println("导出excle失败");
        }
    }
}